package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.interceptor.annotation.InterfaceTokenCheck;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.constant.InterfaceStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * app端的token校验
 * 
 * @author ruoyi
 */
@Component
public abstract class InterfaceTokenCheckInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            InterfaceTokenCheck annotation = method.getAnnotation(InterfaceTokenCheck.class);
            if (annotation != null)
            {
                if (!this.okToken(request))
                {
                    AjaxResult ajaxResult = AjaxResult.error(InterfaceStatus.TOKEN_EXPIRE,"token失效,重新登录");
                    ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                    return false;
                }
            }
            return true;
        }
        else
        {
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * 验证token的有效性
     *
     * @param
     * @return
     * @throws Exception
     */
    public abstract boolean okToken(HttpServletRequest request);
}
